import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_constraint_box_widget/common_constraint_max_width_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_select_date_time_dialog/common_select_date_time_dialog.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/manager/edittext_widget.dart';
import 'package:e_reception_flutter/ui/punch_in_rule/bean/punch_in_rule_bean.dart';
import 'package:e_reception_flutter/utils/common_select_util.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_date_picker/vg_date_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';
import 'package:vg_base/vg_widget_lib.dart';

import 'flexible_duration_set_dialog.dart';

///时长要求
const List<String> durationData = [
  "7.5",
  "8",
  "8.5",
  "9",
  "9.5",
  "10",
  "10.5",
  "11",
  "11.5",
  "12"
];

typedef OnSaveClick = Function();
typedef OnDeleteClick = Function();

/// 设置考勤规则通用部分
class CommonRuleWidget extends StatefulWidget {
  final PunchInRuleBean bean;
  final OnSaveClick onSaveClick;
  final OnDeleteClick onDeleteClick;

  const CommonRuleWidget({
    Key key,
    @required this.bean,
    this.onSaveClick,
    this.onDeleteClick,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return CommonRuleWidgetState();
  }
}

class CommonRuleWidgetState extends State<CommonRuleWidget> {
  PunchInRuleBean bean;

  VoidCallback listener;

  @override
  void initState() {
    bean = widget.bean;
    super.initState();
    listener = () {
      setState(() {
        // print("数据变化了${bean.toString()}");
      });
    };
    bean.addListener(listener);
  }

  @override
  void dispose() {
    bean.removeListener(listener);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        onDutyTime(context),
        _toSplitLineWidget(),
        offDutyTime(context),
        _toSplitLineWidget(),
        durationTime(context),
        _buttonWidget(),
        Spacer(),
        _deleteWidget(),
      ],
    );
  }

  ///上班时间
  onDutyTime(BuildContext context) {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Row(
        children: [
          Expanded(
            child: EditTextWidget(
              title: "上班时间",
              hintText: "请选择",
              customWidget: (Widget titleWidget, Widget textFieldWidget,
                  Widget leftWidget, Widget rightWidget) {
                return Row(
                  children: <Widget>[
                    leftWidget,
                    Expanded(
                      child: GestureDetector(
                        behavior: HitTestBehavior.translucent,
                        onTap: () async {
                          Map result = await CommonSelectDateTimeDialog
                              .navigatorPushDialog(
                                  context, VgCupertinoDatePickerMode.time,
                                  initDateTime:
                                      PunchInRuleBean.getFormatDateTime5min(
                                          bean.onDutyTime)??PunchInRuleBean.getFormatDateTime5min(
                                          bean.offDutyTime,minus5Min: true)??PunchInRuleBean.getFormatDateTime5min(
                          DateUtil.formatDate(DateTime.now(),format: 'HH:mm')),
                                  maxDateTime:
                                      PunchInRuleBean.getFormatDateTime5min(
                                    bean.offDutyTime,minus5Min: true
                                  ),
                                  minuteInterval: 5,
                                  showClear: true);
                          if (result == null) {
                            return;
                          }
                          DateTime dateTime = result[
                              CommonSelectDateTimeDialog.RESULT_DATE_TIME];
                          bean.onDutyTime =
                              PunchInRuleBean.getDateTimeToSecond(dateTime);
                          if(bean.onDutyTime==null){
                            //清空时清除弹性
                            bean.onDutyTimeCheck=false;
                            bean.onDutyFlexibleTime = null;
                          }
                        },
                        child: Row(
                          children: <Widget>[
                            titleWidget,
                            CommonConstraintMaxWidthWidget(
                              maxWidth: ScreenUtils.screenW(context) / 5,
                              child: _selectedText(bean.onDutyTime ?? "请选择",
                                  selected: bean.onDutyTime != null),
                            ),
                            Spacer(),
                            Container(
                              width: 13,
                              height: 10,
                              child: Image.asset(
                                'images/icon_arrow_down.png',
                                width: 11,
                                height: 6,
                              ),
                            ),
                            SizedBox(
                              width: 22,
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
          Container(
            color: Color(0xff5e687c),
            height: 20,
            width: 1,
          ),
          _setOnDutyFlexibleDuration()
        ],
      ),
    );
  }

  ///下班时间
  offDutyTime(BuildContext context) {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Row(
        children: [
          Expanded(
            child: EditTextWidget(
              title: "下班时间",
              hintText: "请选择",
              customWidget: (Widget titleWidget, Widget textFieldWidget,
                  Widget leftWidget, Widget rightWidget) {
                return Row(
                  children: <Widget>[
                    leftWidget,
                    Expanded(
                      child: GestureDetector(
                        behavior: HitTestBehavior.translucent,
                        onTap: () async {
                          Map result = await CommonSelectDateTimeDialog
                              .navigatorPushDialog(
                                  context, VgCupertinoDatePickerMode.time,
                                  initDateTime:
                                      PunchInRuleBean.getFormatDateTime5min(
                                          bean.offDutyTime)??PunchInRuleBean.getFormatDateTime5min(
                                          bean.onDutyTime,plus5min: true)??PunchInRuleBean.getFormatDateTime5min(
                                          DateUtil.formatDate(DateTime.now(),format: 'HH:mm'),plus5min: true),
                                  minDateTime:
                                      PunchInRuleBean.getFormatDateTime5min(
                                          bean.onDutyTime,plus5min: true),
                                  maxDateTime: null,
                                  minuteInterval: 5,
                                  showClear: true);
                          if (result == null) {
                            return;
                          }
                          DateTime dateTime = result[
                              CommonSelectDateTimeDialog.RESULT_DATE_TIME];
                          bean.offDutyTime =
                              PunchInRuleBean.getDateTimeToSecond(dateTime);
                          if(bean.offDutyTime==null){
                            //清空时清除弹性
                            bean.offDutyTimeCheck=false;
                            bean.offDutyFlexibleTime = null;
                          }
                        },
                        child: Row(
                          children: <Widget>[
                            titleWidget,
                            CommonConstraintMaxWidthWidget(
                              maxWidth: ScreenUtils.screenW(context) / 5,
                              child: _selectedText(bean.offDutyTime ?? "请选择",
                                  selected: bean.offDutyTime != null),
                            ),
                            Spacer(),
                            Container(
                              width: 13,
                              height: 10,
                              child: Image.asset(
                                'images/icon_arrow_down.png',
                                width: 11,
                                height: 6,
                              ),
                            ),
                            SizedBox(
                              width: 22,
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
          Container(
            color: Color(0xff5e687c),
            height: 20,
            width: 1,
          ),
          _setOffDutyFlexibleDuration()
        ],
      ),
    );
  }

  ///弹性时长开关
  Container checkBox(bool check) {
    return Container(
      height: 50,
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(left: 14, right: 6),
      child: check ?? false
          ? Container(
              width: 14,
              height: 14,
              alignment: Alignment.center,
              foregroundDecoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  border: Border.all(
                      style: BorderStyle.solid,
                      color: ThemeRepository.getInstance()
                          .getPrimaryColor_1890FF(),
                      width: 3),
                  borderRadius: BorderRadius.all(Radius.circular(2))),
              child: SizedBox(
                child: Icon(
                  Icons.check_box,
                  color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                  size: 14,
                ),
              ))
          : Container(
              width: 14,
              height: 14,
              foregroundDecoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  border: Border.all(color: Color(0xff5e687c), width: 1),
                  borderRadius: BorderRadius.all(Radius.circular(2))),
            ),
    );
  }

  Widget _selectedText(String text, {bool selected = false}) {
    return Text(
      text ?? '',
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      style: TextStyle(
          color: selected ? Color(0xffd0e0f7) : Color(0xff5e687c),
          fontSize: 14),
    );
  }

  ///分割线
  Widget _toSplitLineWidget() {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      padding: const EdgeInsets.only(left: 15),
      height: 0.5,
      child: Container(
        color: ThemeRepository.getInstance().getLineColor_3A3F50(),
      ),
    );
  }

  ///时长要求
  durationTime(BuildContext context) {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Row(
        children: [
          Expanded(
            child: EditTextWidget(
              title: "时长要求",
              hintText: "请选择",
              isShowGoIcon: false,
              isShowRedStar: false,
              readOnly: true,
              customWidget: (Widget titleWidget, Widget textFieldWidget,
                  Widget leftWidget, Widget rightWidget) {
                return Row(
                  children: [
                    leftWidget,
                    titleWidget,
                    Expanded(
                      child: _durationContent(),
                    )
                  ],
                );
              },
            ),
          ),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              bean.durationEnable = !(bean.durationEnable ?? false);
              if (!(bean.durationEnable ?? false)) {
                //关闭时清除时长
                bean.duration = null;
              } else {
                //开启时设置默认值
                bean.setDefaultDurationValue();
              }
              VgToolUtils.removeAllFocus(context);
            },
            child: Padding(
              padding: const EdgeInsets.all(15.0),
              child: Image.asset(
                bean.durationEnable ?? false
                    ? "images/switch_open.png"
                    : "images/switch_close.png",
                width: 36,
                gaplessPlayback: true,
              ),
            ),
          ),
        ],
      ),
    );
  }

  ///时长要求内容
  _durationContent() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        SelectUtil.showListSelectDialog(
            context: context,
            title: "时长要求",
            rightText: "小时",
            positionStr: ((bean.duration ?? 0) / (60 * 60 ))
                .toString()
                .replaceAll('.0', ''),
            textList: durationData,
            onSelect: (dynamic value) {
              bean.durationEnable = true;
              double hourD = (double.parse(value));
              bean.duration = (hourD * 60 * 60 ).toInt();
            });
      },
      child: Row(
        children: [
          Flexible(
            child: _selectedText(
                (bean.durationEnable ?? false)
                    ? PunchInRuleBean.formatDurationTimeString(bean.duration)
                    : bean.getDefaultDuration(),
                selected: bean.durationEnable ?? false),
          ),
          Container(
            height: 35,
            padding: EdgeInsets.only(top: 2, left: 4),
            child: Image.asset(
              'images/icon_arrow_down_gray.png',
              width: 7,
              height: 4,
              color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            ),
          ),
          Spacer()
        ],
      ),
    );
  }

  ///设置上班弹性时长
  _setOnDutyFlexibleDuration() {
    return Row(
      children: [
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          child: checkBox(bean.onDutyTimeCheck),
          onTap: () async {
            if ((bean.onDutyTimeCheck ?? false)) {
              bean.onDutyTimeCheck = false;
              bean.onDutyFlexibleTime = null;
            } else {
              if(StringUtils.isEmpty(bean.onDutyTime)){
                ToastUtils.toast(context:context,msg:'请设置上班时间');
                return;
              }
              SelectUtil.showListSelectDialog(
                  context: context,
                  title: "上班弹性时长",
                  subTitle: '在该时间范围内迟到不视为异常',
                  confirmText: "保存",
                  positionStr: "${bean.onDutyFlexibleTime!=null?(bean.onDutyFlexibleTime~/60).toString():'5'}分钟",
                  textList: timeData,
                  onSelect: (String value) {
                    bean.onDutyFlexibleTime = int.parse(value.replaceAll('分钟', ''))*60;
                    bean.onDutyTimeCheck = bean.onDutyFlexibleTime != null;
                  });
              // int result = await FlexibleDurationSetDialog.navigatorPushDialog(
              //     context,
              //     title: "上班弹性时长",
              //     initValue: bean.onDutyFlexibleTime!=null?(bean.onDutyFlexibleTime~/60):null);
              // if (result != null) {
              //   bean.onDutyFlexibleTime = result*60;
              //   bean.onDutyTimeCheck = bean.onDutyFlexibleTime != null;
              // }
            }
          },
        ),
        GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () async {
              if(StringUtils.isEmpty(bean.onDutyTime)){
                ToastUtils.toast(context:context,msg:'请设置上班时间');
                return;
              }
              SelectUtil.showListSelectDialog(
                  context: context,
                  title: "上班弹性时长",
                  subTitle: '在该时间范围内迟到不视为异常',
                  confirmText: "保存",
                  positionStr: "${bean.onDutyFlexibleTime!=null?(bean.onDutyFlexibleTime~/60).toString():'5'}分钟",
                  textList: timeData,
                  onSelect: (String value) {
                    bean.onDutyFlexibleTime = int.parse(value.replaceAll('分钟', ''))*60;
                    bean.onDutyTimeCheck = bean.onDutyFlexibleTime != null;
                  });
              // int result = await FlexibleDurationSetDialog.navigatorPushDialog(
              //     context,
              //     title: "上班弹性时长",
              //     initValue: bean.onDutyFlexibleTime!=null?(bean.onDutyFlexibleTime~/60):null);
              // if (result != null) {
              //   bean.onDutyFlexibleTime = result*60;
              // }
              // bean.onDutyTimeCheck = bean.onDutyFlexibleTime != null;
            },
            child: Container(
              width: 115,
              height: 50,
              alignment: Alignment.centerLeft,
              child: Row(
                children: [
                  _selectedText(
                      bean.onDutyFlexibleTime == null
                          ? "设置弹性时长"
                          : '弹性${bean.onDutyFlexibleTime~/60}分钟',
                      selected: bean.onDutyFlexibleTime != null),
                  if (bean.onDutyFlexibleTime != null)
                    Container(
                      height: 35,
                      padding: EdgeInsets.only(top: 2, left: 4),
                      child: Image.asset(
                        'images/icon_arrow_down_gray.png',
                        width: 7,
                        height: 4,
                        color: ThemeRepository.getInstance()
                            .getPrimaryColor_1890FF(),
                      ),
                    ),
                ],
              ),
            )),
      ],
    );
  }

  ///设置下班弹性时长
  _setOffDutyFlexibleDuration() {
    return Row(
      children: [
        GestureDetector(
          child: checkBox(bean.offDutyTimeCheck),
          onTap: () async {
            if ((bean.offDutyTimeCheck ?? false)) {
              bean.offDutyTimeCheck = false;
              bean.offDutyFlexibleTime = null;
            } else {
              if(StringUtils.isEmpty(bean.offDutyTime)){
                ToastUtils.toast(context:context,msg:'请设置下班时间');
                return;
              }
              SelectUtil.showListSelectDialog(
                  context: context,
                  title: "下班弹性时长",
                  subTitle: '在该时间范围内提前下班不视为异常',
                  confirmText: "保存",
                  positionStr:"${ bean.offDutyFlexibleTime!=null?(bean.offDutyFlexibleTime~/60).toString():'5'}分钟",
                  textList: timeData,
                  onSelect: (String value) {
                    bean.offDutyFlexibleTime = int.parse(value.replaceAll('分钟', ''))*60;
                    bean.offDutyTimeCheck = bean.offDutyFlexibleTime != null;
                  });
              // int result = await FlexibleDurationSetDialog.navigatorPushDialog(
              //     context,
              //     title: "下班弹性时长",
              //     initValue: bean.offDutyFlexibleTime!=null?(bean.offDutyFlexibleTime~/60):null);
              // if (result != null) {
              //   bean.offDutyFlexibleTime = result*60;
              //   bean.offDutyTimeCheck = bean.offDutyFlexibleTime != null;
              // }
            }
          },
        ),
        GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () async {
              if(StringUtils.isEmpty(bean.offDutyTime)){
                ToastUtils.toast(context:context,msg:'请设置下班时间');
                return;
              }
              SelectUtil.showListSelectDialog(
                  context: context,
                  title: "下班弹性时长",
                  subTitle: '在该时间范围内提前下班不视为异常',
                  confirmText: "保存",
                  positionStr:"${ bean.offDutyFlexibleTime!=null?(bean.offDutyFlexibleTime~/60).toString():'5'}分钟",
                  textList: timeData,
                  onSelect: (String value) {
                    bean.offDutyFlexibleTime = int.parse(value.replaceAll('分钟', ''))*60;
                    bean.offDutyTimeCheck = bean.offDutyFlexibleTime != null;
                  });
              // int result = await FlexibleDurationSetDialog.navigatorPushDialog(
              //     context,
              //     title: "下班弹性时长",
              //     initValue: bean.offDutyFlexibleTime!=null?(bean.offDutyFlexibleTime~/60):null);
              // if (result != null) {
              //   bean.offDutyFlexibleTime = result*60;
              //   bean.offDutyTimeCheck = bean.offDutyFlexibleTime != null;
              // }
            },
            child: Container(
              width: 115,
              height: 50,
              alignment: Alignment.centerLeft,
              child: Row(
                children: [
                  _selectedText(
                      bean.offDutyFlexibleTime == null
                          ? "设置弹性时长"
                          : '弹性${(bean.offDutyFlexibleTime??0)~/60}分钟',
                      selected: bean.offDutyFlexibleTime != null),
                  if (bean.offDutyFlexibleTime != null)
                    Container(
                      height: 35,
                      padding: EdgeInsets.only(top: 2, left: 4),
                      child: Image.asset(
                        'images/icon_arrow_down_gray.png',
                        width: 7,
                        height: 4,
                        color: ThemeRepository.getInstance()
                            .getPrimaryColor_1890FF(),
                      ),
                    )
                ],
              ),
            )),
      ],
    );
  }

  ///提交按钮
  Widget _buttonWidget() {
    return Container(
      width: double.infinity,
      height: 40,
      margin: EdgeInsets.only(left: 12, right: 12, top: 30),
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: bean.canCommit(),
        height: 40,
        unSelectBgColor:
            ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 12,
            fontWeight: FontWeight.w600),
        selectedTextStyle: TextStyle(
            color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
        text: "保存并启用",
        textSize: 15,
        onTap: () {
          //提交按钮
          widget.onSaveClick?.call();
          // 触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        },
      ),
    );
  }

  ///删除
  _deleteWidget() {
    return Visibility(
      visible: bean.id != null,
      child: GestureDetector(
          onTap: () {
            widget.onDeleteClick?.call();
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 40, horizontal: 50),
            child: Text(
              "删除规则",
              style: TextStyle(
                  color:
                      ThemeRepository.getInstance().getMinorRedColor_F95355(),
                  fontSize: 15),
            ),
          )),
    );
  }
}
